import React from 'react';
import './index.scss';
import { Form, Input, Button, message } from 'antd';
import { EyeTwoTone, EyeInvisibleOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import { encryptStr, verifyAccountPwd } from 'utils/tools';
import {
  setSystemConfigAsynic,
  setToken,
  setUserInfoLater,
  setLoginInfo,
  setUserInfo,
} from 'store/root/action';
import { connect } from 'react-redux';
import { JSONObject } from '../../schema/common';
import { RouteConfigComponentProps } from 'react-router-config';
import { modifySysUserPwd } from 'admin/servers/servers';
import { logoutSys } from 'utils';

interface IState {
  // 状态
  loading: boolean;
}

/**
 * 功能：修改密码
 * 场景：用户登录系统，当检测到密码强度较低时修改密码
 */
class ResetNewPwd extends React.Component<{}, IState> {
  // form的表单引用
  form: React.RefObject<FormInstance>;

  constructor(prop: {}) {
    super(prop);
    this.form = React.createRef();
    this.state = {
      loading: false,
    };
  }

  componentDidMount() {
    if (process.env.REACT_APP_LOGIN_NO_CHECK !== '1') {
      this.checkToken();
    }
  }
  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  };
  /**检测token是否为空 */
  checkToken = () => {
    // 如果token无值，直接跳转登录
    const {
      token,
      loginInfo: { pwd },
    } = this.props as any;
    if (!(token && pwd)) {
      // token为空，或者登录密码为空，直接返回登录页面
      (this.props as any).history.push('/webapp/login');
    } else {
      console.log('存在有效的token和登录密码👌🏻，可以【设置新密码】操作=====');
    }
  };

  /**提交信息修改密码*/
  onSubmit = () => {
    (this.form.current as FormInstance).validateFields().then(async values => {
      const {
        loginInfo: { pwd },
      } = this.props as any;
      const newPassword = encryptStr(values.newPwd);
      this.setState({
        loading: true,
      });
      try {
        await modifySysUserPwd(pwd, newPassword);
        message.success('密码修改成功');
        logoutSys(true);
      } catch (error) {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      }
      this.setState({
        loading: false,
      });
    });
  };

  render() {
    const { loading } = this.state;
    const { form } = this;
    return (
      <div className="page-reset-new-pwd">
        <div className="box">
          <div className="tip">密码强度较低，请设置新密码</div>
          <Form ref={form}>
            <Form.Item
              label="新密码"
              name="newPwd"
              rules={verifyAccountPwd}
              validateFirst={true}
              getValueFromEvent={event => {
                // 圆点符号包含逗号，所以过滤逗号需单独处理
                return event.target.value
                  .replace(/,+/g, '')
                  .replace(/[^a-zA-Z0-9~@#\$*%\^:;_.+-\/]+/g, '')
                  .slice(0, 30);
              }}
            >
              <Input.Password
                minLength={8}
                maxLength={30}
                placeholder="8位以上字符，需包含大写字母、小写字母、数字和特殊字符中的三类"
                iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
              />
            </Form.Item>
            <div style={{ lineHeight: '40px', textAlign: 'center' }}>
              <Button
                className="btn"
                size="large"
                type="primary"
                loading={loading}
                onClick={this.onSubmit}
              >
                {loading ? '请稍后' : '确定'}
              </Button>
            </div>
          </Form>
        </div>
      </div>
    );
  }
}

// state 注入props
const mapStateToProps = (state: JSONObject) => {
  return {
    systemConfig: state.systemConfig,
    token: state.token,
    loginInfo: state.loginInfo,
  };
};

// action 注入props
const mapDispatchToProps = {
  setSystemConfigAsynic,
  setToken,
  setUserInfo,
  setLoginInfo,
  setUserInfoLater,
};

export default connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true })(
  ResetNewPwd
) as React.ComponentType<RouteConfigComponentProps<any>>;
